// #include <myhead.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <dirent.h>
// #include<pthread.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <wait.h>
#include <time.h>
#include <sys/time.h>
// #include <sqlite3.h>
#include "tool.h"
// 驱动相关驱动所需头文件
#include <sys/ioctl.h>
#include <sys/select.h>
#define PRINT_ERROR_APP(msg)                                           \
	do                                                                 \
	{                                                                  \
		printf("error : %s ,in line %d\n", strerror(errno), __LINE__); \
		printf("%s\n", msg);                                           \
		exit(-1);                                                      \
	} while (0)

#include "m74hc595_driver.h"
#include "led_driver.h"
#include "fan_motor_driver.h"
// E3 读温度 tem E0
// E5 读湿度 hum
typedef unsigned char u8;
typedef unsigned short u16;

extern int sockfd;
extern sem_t sem; // 保护xxx_stat和xxx_global 以及 文件读写
extern sem_t auto_sem; // 保护auto_open
extern sem_t copy_sem; // 保护通过线程传参的地址进行拷贝的数据的完整性
extern char auto_open;
int led_stat = 0;
int fan_stat = 0;
int motor_stat = 0;
char ID[20] = {0};
char PW[20] = {0};
// myprotocol_t global_buf;

float tem_global = 0;
float hum_global = 0;
float lx_global = 0;

int read_config(myprotocol_t *buf)
{
	FILE *fp = NULL;
	fp = fopen(CONFIG_PATH, "r");
	if (NULL == fp)
	{
		perror("fopen error");
		return -1;
	}
	char file_buf[32] = {0};
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		// 提取用户名，假定格式为 id{username}
		sscanf(file_buf, "id{%[^}]}", buf->user_info.id);
	}
	strcpy(ID, buf->user_info.id);
	memset(file_buf, 0, sizeof(file_buf));
	// 读取密码行
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		// 提取密码，假定格式为 pw{password}
		sscanf(file_buf, "pw{%[^}]}", buf->user_info.pw); // %[^}]是一个扫描集,它告诉sscanf读取直到遇到}为止的所有字符
	}
	strcpy(PW, buf->user_info.pw);
	fclose(fp);
	return 0;
}

int read_threshold_config(myprotocol_t *buf)
{
	FILE *fp = NULL;
	fp = fopen(CONFIG_PATH, "r");
	if (NULL == fp)
	{
		perror("fopen error");
		return -1;
	}
	char file_buf[32] = {0};
	char temp[32] = {0};
	// 跳过前两行
	fgets(file_buf, sizeof(file_buf), fp);
	fgets(file_buf, sizeof(file_buf), fp);
	memset(file_buf, 0, sizeof(file_buf));
	// 读取温度上限
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		sscanf(file_buf, "tem_max{%[^}]}", temp);
		buf->threshold_info.tem_max = atof(temp); // 没想到还有如此好用的接口
	}
	memset(file_buf, 0, sizeof(file_buf));
	memset(temp, 0, sizeof(temp));
	// 读取温度下限
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		sscanf(file_buf, "tem_min{%[^}]}", temp);
		buf->threshold_info.tem_min = atof(temp);
	}
	memset(file_buf, 0, sizeof(file_buf));
	memset(temp, 0, sizeof(temp));
	// 读取湿度上限
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		sscanf(file_buf, "hum_max{%[^}]}", temp);
		buf->threshold_info.hum_max = atof(temp);
	}
	memset(file_buf, 0, sizeof(file_buf));
	memset(temp, 0, sizeof(temp));
	// 读取湿度下限
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		sscanf(file_buf, "hum_min{%[^}]}", temp);
		buf->threshold_info.hum_min = atof(temp);
	}
	memset(file_buf, 0, sizeof(file_buf));
	memset(temp, 0, sizeof(temp));
	// 读取光照上限
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		sscanf(file_buf, "lux_max{%[^}]}", temp);
		buf->threshold_info.lx_max = atof(temp);
	}
	memset(file_buf, 0, sizeof(file_buf));
	memset(temp, 0, sizeof(temp));
	// 读取光照下限
	if (fgets(file_buf, sizeof(file_buf), fp) != NULL)
	{
		sscanf(file_buf, "lux_min{%[^}]}", temp);
		buf->threshold_info.lx_min = atof(temp);
	}
	// 读取设备状态
	// 读取照明设备状态
	buf->env_info.dev_state &= ~(0x01 << 0);
	buf->env_info.dev_state |= (led_stat << 0);
	// 读取空调( 风扇 )设备状态
	buf->env_info.dev_state &= ~(0x03 << 1);
	buf->env_info.dev_state |= (fan_stat << 1);
	// 读取加湿器( 马达 )设备状态
	buf->env_info.dev_state &= ~(0x01 << 3);
	buf->env_info.dev_state |= (motor_stat << 3);

	fclose(fp);
	return 0;
}

int write_threshold_config(myprotocol_t *buf)
{
	FILE *fp = NULL;
	fp = fopen(CONFIG_PATH, "w");
	if (NULL == fp)
	{
		perror("fopen error");
		return -1;
	}
	// 写入用户名
	fprintf(fp, "id{%s}\n", ID);
	// 写入密码
	fprintf(fp, "pw{%s}\n", PW);
	// 写入温度上限
	fprintf(fp, "tem_max{%f}\n", buf->threshold_info.tem_max);
	// 写入温度下限
	fprintf(fp, "tem_min{%f}\n", buf->threshold_info.tem_min);
	// 写入湿度上限
	fprintf(fp, "hum_max{%f}\n", buf->threshold_info.hum_max);
	// 写入湿度下限
	fprintf(fp, "hum_min{%f}\n", buf->threshold_info.hum_min);
	// 写入光照上限
	fprintf(fp, "lux_max{%f}\n", buf->threshold_info.lx_max);
	// 写入光照下限
	fprintf(fp, "lux_min{%f}\n", buf->threshold_info.lx_min);

	fclose(fp);
	return 0;
}

int net_init(const char *ip, const int port)
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0)
	{
		perror("socket error");
		return -1;
	}
	struct sockaddr_in seraddr;
	seraddr.sin_family = AF_INET;
	seraddr.sin_port = htons(port);
	seraddr.sin_addr.s_addr = inet_addr(ip);
	if (connect(sockfd, (struct sockaddr *)&seraddr, sizeof(seraddr)) < 0)
	{
		perror("connect error");
		return -1;
	}
	return sockfd;
}

int init_dev(void)
{
	// 关灯
	int fd = open("/dev/led_driver1", O_RDWR);
	if (-1 == fd)
	{
		perror("open error");
		return -1;
	}
	led_stat = 0;
	ioctl(fd, LEDX_IOWR(1), &led_stat);
	ioctl(fd, LEDX_IOWR(2), &led_stat);
	ioctl(fd, LEDX_IOWR(3), &led_stat);
	close(fd);
	// 关电扇( 空调 )
	fd = open("/dev/fan_driver", O_RDWR);
	if (-1 == fd)
	{
		perror("open fan_driver error");
		return -1;
	}
	fan_stat = fan_off;
	ioctl(fd, FAN_IOWR(fan_off), &fan_stat);
	close(fd);
	// 关加湿器( 马达 )
	fd = open("/dev/motor_driver", O_RDWR);
	if (-1 == fd)
	{
		perror("open motor_driver error");
		return -1;
	}
	motor_stat = motor_off;
	ioctl(fd, MOTOR_IOWR(motor_off), &motor_stat);
	close(fd);
	return 0;
}

void *get_envdata_thread(void *arg)
{
	// 获取环境数据
	sem_wait(&copy_sem);
	myprotocol_t buf = *(myprotocol_t *)arg;
	sem_post(&copy_sem);
	// 光照强度 填入
	buf.env_info.lx = lx_global;
	// 当前环境数据 温湿度填入
	buf.env_info.tem = tem_global;
	buf.env_info.hum = hum_global;
	// 阈值填入 设备状态填入
	sem_wait(&sem);
	read_threshold_config(&buf);
	sem_post(&sem);
	send(sockfd, &buf, sizeof(buf), 0);
	return NULL;
}

void *set_threshold_thread(void *arg)
{
	// 设置阈值
	sem_wait(&copy_sem);
	myprotocol_t buf = *(myprotocol_t *)arg;
	sem_post(&copy_sem);
	// 写入阈值
	sem_wait(&sem);
	write_threshold_config(&buf);
	sem_post(&sem);
	// 就算是没用的数据也要发过去 不然x86的服务器recv会卡住
	if (-1 == send(sockfd, &buf, sizeof(buf), 0))
	{
		perror("send error");
	}

	return NULL;
}

void *control_dev_thread(void *arg)
{
	// 控制设备
	sem_wait(&copy_sem);
	myprotocol_t buf = *(myprotocol_t *)arg;
	sem_post(&copy_sem);
	sem_wait(&sem);
	if (buf.env_info.dev_state & 0x01)
	{
		// 开灯
		int fd = open("/dev/led_driver1", O_RDWR);
		if (-1 == fd)
		{
			perror("open error");
			return NULL;
			// return (void *)-1;
		}
		led_stat = 1;
		ioctl(fd, LEDX_IOWR(1), &led_stat);
		ioctl(fd, LEDX_IOWR(2), &led_stat);
		ioctl(fd, LEDX_IOWR(3), &led_stat);
		close(fd);
	}
	else
	{
		// 关灯
		int fd = open("/dev/led_driver1", O_RDWR);
		if (-1 == fd)
		{
			perror("open error");
			return NULL;
			// return (void *)-1;
		}
		led_stat = 0;
		ioctl(fd, LEDX_IOWR(1), &led_stat);
		ioctl(fd, LEDX_IOWR(2), &led_stat);
		ioctl(fd, LEDX_IOWR(3), &led_stat);
		close(fd);
	}
	if (((buf.env_info.dev_state >> 1) & 0x03) == 0x01)
	{
		// 空调( 电扇 )1档
		int fd = open("/dev/fan_driver", O_RDWR);
		if (-1 == fd)
		{
			perror("open fan_driver error");
			return NULL;
			// return (void *)-1;
		}
		fan_stat = fan_1;
		ioctl(fd, FAN_IOWR(fan_1), &fan_stat);
		close(fd);
	}
	else if (((buf.env_info.dev_state >> 1) & 0x03) == 0x02)
	{
		// 空调( 电扇 )2档
		int fd = open("/dev/fan_driver", O_RDWR);
		if (-1 == fd)
		{
			perror("open fan_driver error");
			return NULL;
			// return (void *)-1;
		}
		fan_stat = fan_2;
		ioctl(fd, FAN_IOWR(fan_2), &fan_stat);
		close(fd);
	}
	else if (((buf.env_info.dev_state >> 1) & 0x03) == 0x03)
	{
		// 空调( 电扇 )3档
		int fd = open("/dev/fan_driver", O_RDWR);
		if (-1 == fd)
		{
			perror("open fan_driver error");
			return NULL;
			// return (void *)-1;
		}
		fan_stat = fan_3;
		ioctl(fd, FAN_IOWR(fan_3), &fan_stat);
		close(fd);
	}
	else
	{
		// 关电扇( 空调 )
		int fd = open("/dev/fan_driver", O_RDWR);
		if (-1 == fd)
		{
			perror("open fan_driver error");
			return NULL;
			// return (void *)-1;
		}
		fan_stat = fan_off;
		ioctl(fd, FAN_IOWR(fan_off), &fan_stat);
		close(fd);
	}
	if ((buf.env_info.dev_state >> 3) & 0x01)
	{
		// 开加湿器( 马达 )
		int fd = open("/dev/motor_driver", O_RDWR);
		if (-1 == fd)
		{
			perror("open motor_driver error");
			return NULL;
			// return (void *)-1;
		}
		motor_stat = motor_1;
		ioctl(fd, MOTOR_IOWR(motor_on), &motor_stat);
		close(fd);
	}
	else
	{
		// 关加湿器( 马达 )
		int fd = open("/dev/motor_driver", O_RDWR);
		if (-1 == fd)
		{
			perror("open motor_driver error");
			return NULL;
			// return (void *)-1;
		}
		motor_stat = motor_off;
		ioctl(fd, MOTOR_IOWR(motor_off), &motor_stat);
		close(fd);
	}
	sem_post(&sem);
	send(sockfd, &buf, sizeof(buf), 0);
	return NULL;
}

void *maintain_dev_thread(void *arg)
{
	// 根据阈值维护设备状态( 环境状态 )
	myprotocol_t buf = {0};
	while (1)
	{
		sem_wait(&auto_sem);
		if (auto_open)
		{
			sem_post(&auto_sem);
			sem_wait(&sem);
			int fd;
			read_threshold_config(&buf); // 每次都得读
			if (buf.threshold_info.tem_max < tem_global)
			{
				// 说明温度过高
				fd = open("/dev/fan_driver", O_RDWR);
				if (-1 == fd)
				{
					perror("open fan_driver error");
					return NULL;
					// return (void *)-1;
				}
				fan_stat = fan_2;
				ioctl(fd, FAN_IOWR(fan_2), &fan_stat);
			}
			else if (buf.threshold_info.tem_min > tem_global)
			{
				// 说明温度过低 本设备暂不做处理
				fd = open("/dev/fan_driver", O_RDWR);
				if (-1 == fd)
				{
					perror("open fan_driver error");
					return NULL;
					// return (void *)-1;
				}
				fan_stat = fan_off;
				ioctl(fd, FAN_IOWR(fan_off), &fan_stat);
			}
			else
			{
				// 说明温度正常
				fd = open("/dev/fan_driver", O_RDWR);
				if (-1 == fd)
				{
					perror("open fan_driver error");
					return NULL;
					// return (void *)-1;
				}
				fan_stat = fan_off;
				ioctl(fd, FAN_IOWR(fan_off), &fan_stat);
			}
			if (buf.threshold_info.hum_min > hum_global)
			{
				// 说明湿度过低
				fd = open("/dev/motor_driver", O_RDWR);
				if (-1 == fd)
				{
					perror("open motor_driver error");
					return NULL;
					// return (void *)-1;
				}
				motor_stat = motor_1;
				ioctl(fd, MOTOR_IOWR(motor_on), &motor_stat);
			}
			else if (buf.threshold_info.hum_max < hum_global)
			{
				// 说明湿度过高 本设备暂不做处理
				fd = open("/dev/motor_driver", O_RDWR);
				if (-1 == fd)
				{
					perror("open motor_driver error");
					return NULL;
					// return (void *)-1;
				}
				motor_stat = motor_off;
				ioctl(fd, MOTOR_IOWR(motor_off), &motor_stat);
			}
			else
			{
				// 说明湿度正常
				fd = open("/dev/motor_driver", O_RDWR);
				if (-1 == fd)
				{
					perror("open motor_driver error");
					return NULL;
					// return (void *)-1;
				}
				motor_stat = motor_off;
				ioctl(fd, MOTOR_IOWR(motor_off), &motor_stat);
			}
			if (buf.threshold_info.lx_min > lx_global)
			{
				// 说明光照过低
				fd = open("/dev/led_driver1", O_RDWR);
				if (-1 == fd)
				{
					perror("open error");
					return NULL;
					// return (void *)-1;
				}
				led_stat = 1;
				ioctl(fd, LEDX_IOWR(1), &led_stat);
				ioctl(fd, LEDX_IOWR(2), &led_stat);
				ioctl(fd, LEDX_IOWR(3), &led_stat);
			}
			else if (buf.threshold_info.lx_max < lx_global)
			{
				// 说明光照过高 本设备暂不做处理
				fd = open("/dev/led_driver1", O_RDWR);
				if (-1 == fd)
				{
					perror("open error");
					return NULL;
					// return (void *)-1;
				}
				led_stat = 0;
				ioctl(fd, LEDX_IOWR(1), &led_stat);
				ioctl(fd, LEDX_IOWR(2), &led_stat);
				ioctl(fd, LEDX_IOWR(3), &led_stat);
			}
			else
			{
				// 说明光照正常
				fd = open("/dev/led_driver1", O_RDWR);
				if (-1 == fd)
				{
					perror("open error");
					return NULL;
					// return (void *)-1;
				}
				led_stat = 0;
				ioctl(fd, LEDX_IOWR(1), &led_stat);
				ioctl(fd, LEDX_IOWR(2), &led_stat);
				ioctl(fd, LEDX_IOWR(3), &led_stat);
			}
			close(fd);
			sem_post(&sem);
		}
		else
		{
			sem_post(&auto_sem);
		}
		sleep(3); // 每3秒进行一次环境温度的维护
	}

	return NULL;
}

void *display_thread(void *arg)
{
	u8 reg;
	u16 data;
	u8 ge, shi, xiaoshu1, xiaoshu2;
	int flag = 1;
	int fd, fd2, fd3;
	int can_read;
	int hum, tem;
	fd = open("/dev/si7006_driver", O_RDWR);
	fd2 = open("/dev/m74hc595_driver", O_RDWR);
	if (-1 == fd2)
		PRINT_ERROR_APP("open error");
	if (-1 == fd)
	{
		PRINT_ERROR_APP("open error");
		close(fd2);
	}
	fd3 = open("/dev/ap3216c_driver", O_RDWR);
	if (-1 == fd3)
	{
		PRINT_ERROR_APP("open error");
		close(fd);
		close(fd2);
	}
	// 光照强度 填入
	short light_buf;
	while (1)
	{
		ioctl(fd, NIXIE_IOWR(1), &can_read);
		if (can_read)
		{
			sem_wait(&sem);
			reg = 0xE3;
			write(fd, &reg, sizeof(reg));
			read(fd, &data, sizeof(data));
			tem_global = (175.72 * data / 65536 - 46.85);
			reg = 0xE5;
			write(fd, &reg, sizeof(reg));
			read(fd, &data, sizeof(data));
			hum_global = (125.0 * data / 65536 - 6);
			if (flag)
			{
				tem = tem_global * 100;
				flag = !flag;
			}
			else
			{
				tem = hum_global * 100;
				flag = !flag;
			}
			read(fd3, &light_buf, sizeof(light_buf));
			lx_global = light_buf * 0.35;
			can_read = 0;
			sem_post(&sem);
		}

		xiaoshu2 = (tem % 10);
		xiaoshu1 = (tem / 10 % 10);
		ge = (tem / 100 % 10);
		shi = (tem / 1000 % 10);

		ioctl(fd2, 0xFF, 0);
		ioctl(fd2, NIXIE_IOWR(shi), tube_1);
		ioctl(fd2, 0xFF, 0);
		ioctl(fd2, NIXIE_IOWR(ge), tube_2); // 驱动端已加小数点
		ioctl(fd2, 0xFF, 0);
		ioctl(fd2, NIXIE_IOWR(xiaoshu1), tube_3);
		ioctl(fd2, 0xFF, 0);
		// 显示字母
		if (!flag) // 温度
		{
			ioctl(fd2, NIXIE_IOWR(16), tube_4);
			ioctl(fd2, 0xFF, 0);
		}
		else // 湿度
		{
			ioctl(fd2, NIXIE_IOWR(17), tube_4);
			ioctl(fd2, 0xFF, 0);
		}
	}

	close(fd);
	close(fd2);
	close(fd3);
}